package top.lidee.common.service.twice.applet.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thoughtworks.xstream.core.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lidee.common.dto.AccountInfo;
import top.lidee.common.service.twice.applet.MtStoreCateService;
import top.lidee.common.service.twice.management.MtSecondaryCateSpecialMapService;
import top.lidee.common.service.twice.management.MtUploadCateCertificationLogService;
import top.lidee.framework.enums.CommonExceptionEnum;
import top.lidee.framework.result.GlobalCheck;
import top.lidee.framework.result.PageUtils;
import top.lidee.framework.result.ResponseResult;
import top.lidee.module.backendApi.twice.page.Query;
import top.lidee.repository.mapper.twice.applet.MtStoreCateMapper;
import top.lidee.repository.model.twice.pojo.applet.MtStoreCateEntity;
import top.lidee.repository.model.twice.pojo.management.MtSecondaryCateSpecialMapEntity;
import top.lidee.repository.model.twice.vo.applet.MtSecondaryCateSpecialMapVo;
import top.lidee.repository.model.twice.vo.management.MtStoreCateListTreeVo;
import top.lidee.repository.model.twice.vo.management.MtStoreCateSaveOrUpdateVo;
import top.lidee.utils.CopyBean;
import top.lidee.utils.MyCollUtil;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service("mtStockCateService")
@Slf4j
public class MtStoreCateServiceImpl extends ServiceImpl<MtStoreCateMapper, MtStoreCateEntity> implements MtStoreCateService {

    @Autowired
    private MtSecondaryCateSpecialMapService mtSecondaryCateSpecialMapService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MtStoreCateEntity> page = this.page(
                new Query<MtStoreCateEntity>().getPage(params),
                new QueryWrapper<MtStoreCateEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * @param cateId
     * @return top.lidee.framework.result.ResponseResult
     * @description 根据1级分类查询对应2级分类
     * @author zhangyiheng
     * @date 2024/9/27 11:25
     */
    @Override
    public ResponseResult getSecondaryCateByOne(Integer cateId) {

        MtStoreCateEntity cate = this.getById(cateId);

        if (!Objects.equals(cate.getCatLevel(), 1)) {
            return ResponseResult.errorResult(CommonExceptionEnum.QCR1JFL);
        }

        List<MtStoreCateEntity> list = this.list(Wrappers.<MtStoreCateEntity>lambdaQuery()
                .eq(MtStoreCateEntity::getParentId, cate.getCategoryId()));

        return ResponseResult.okResult(list);
    }

    /**
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 查询所有行业分类 一级分类
     * @author zhangyiheng
     * @date 2024/10/9 11:04
     */
    @Override
    public ResponseResult listLeve1(AccountInfo accountInfo) {
        GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());
        List<MtStoreCateEntity> list = this.list(Wrappers.<MtStoreCateEntity>lambdaQuery()
                .eq(MtStoreCateEntity::getParentId, 0));
        return ResponseResult.okResult(list);
    }

    /**
     * @param accountInfo
     * @return top.lidee.framework.result.ResponseResult
     * @description 查询所有行业分类 树形结构
     * @author zhangyiheng
     * @date 2024/10/8 11:28
     */
    @Override
    public ResponseResult listTree(AccountInfo accountInfo) {
        GlobalCheck.checkManagerAdmin(accountInfo.getManagerId());
        try {
            List<MtStoreCateEntity> list = this.list();
            if (!MyCollUtil.isNotEmpty(list)) {
                return ResponseResult.errorResult(CommonExceptionEnum.DATE_NOT_DATA);
            }


            //树化并排序
            List<MtStoreCateListTreeVo> categoryVos = getCategoryTreeVos(list);

            return MyCollUtil.isNotEmpty(categoryVos) ? new ResponseResult().ok(categoryVos) : ResponseResult.errorResult(CommonExceptionEnum.DATE_NOT_DATA);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseResult.errorResult(CommonExceptionEnum.DATE_NOT_DATA);
        }
    }

    private List<MtStoreCateListTreeVo> getCategoryTreeVos(List<MtStoreCateEntity> list) {
        List<MtStoreCateListTreeVo> vos = CopyBean.copyBeanList(list, MtStoreCateListTreeVo.class);

        Map<Integer, MtStoreCateListTreeVo> map = new HashMap<>();

        for (MtStoreCateListTreeVo categorys : vos) {
            map.put(categorys.getCategoryId(), categorys);
        }

        List<MtStoreCateListTreeVo> categoryVos = new ArrayList<>();

        for (MtStoreCateListTreeVo value : map.values()) {
            MtStoreCateListTreeVo fatherCategory = map.get(value.getParentId());

            if (!Objects.isNull(fatherCategory)) {
                //说明有父分类
                if (CollUtil.isEmpty(fatherCategory.getChildren())) {
                    fatherCategory.setChildren(new ArrayList<>());
                }
                fatherCategory.getChildren().add(value);
                //排序
                categorySonSort(fatherCategory.getChildren());
            } else {
                categoryVos.add(value);
                categorySonSort(categoryVos);
            }
        }
        return categoryVos;
    }

    private void categorySonSort(List<MtStoreCateListTreeVo> sonSort) {

        sonSort.sort(new Comparator<MtStoreCateListTreeVo>() {
            @Override
            public int compare(MtStoreCateListTreeVo o1, MtStoreCateListTreeVo o2) {
                return (o1.getSort() == null ? 0 : o1.getSort()) - (o2.getSort() == null ? 0 : o2.getSort());
            }
        });
    }

    /**
     * @param accountInfo
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 新增/保存分类
     * @author zhangyiheng
     * @date 2024/10/8 11:38
     */
    @Override
    @Transactional
    public ResponseResult savedIn(AccountInfo accountInfo, MtStoreCateSaveOrUpdateVo vo) {
        GlobalCheck.checkAdmin(accountInfo.getManagerId());

        //如果保存的是二级分类，mcc不能为空 如果存在特殊资质，特殊资质集合最少填一条
        if (savaOrUpdateCateCheck(vo)) return ResponseResult.errorResult(CommonExceptionEnum.RJLMCODEBNWK);


        MtStoreCateEntity cate = CopyBean.copyBean(vo, MtStoreCateEntity.class);

        this.save(cate);

        //保存特殊资质信息

        Optional.ofNullable(vo.getSecondaryCateSpecialMap()).ifPresent(item -> {
            //不等于空保存
            item.forEach(po -> po.setCateId(cate.getCategoryId()));
            mtSecondaryCateSpecialMapService.saveBatch(item);
        });

        return ResponseResult.ok();
    }

    private boolean savaOrUpdateCateCheck(MtStoreCateSaveOrUpdateVo vo) {
        //如果保存的是二级分类，mcc不能为空
        if (!Objects.equals(vo.getParentId(), 0)) {
            return Objects.isNull(vo.getSecondaryCateCode());
        }

        //如果存在特殊资质，特殊资质集合最少填一条
        if (Objects.equals(vo.getSpecialQualification(), "0")) {
            if (Objects.isNull(vo.getSecondaryCateSpecialMap())) {
                throw new BeanCreationException("特殊资质集合最少填一条");
            }
        } else {
            //如果不是特殊资质但上传了
//            if (Objects.nonNull(vo.getSecondaryCateSpecialMap())) {
//                throw new BeanCreationException("此店铺行业不需要特殊资质");
//            }
        }

        return false;
    }

    /**
     * @param accountInfo
     * @param cateId
     * @return top.lidee.framework.result.ResponseResult
     * @description 根据id查询
     * @author zhangyiheng
     * @date 2024/10/8 14:20
     */
    @Override
    public ResponseResult info(AccountInfo accountInfo, Integer cateId) {
        GlobalCheck.checkAdmin(accountInfo.getManagerId());
        MtStoreCateEntity cate = this.getById(cateId);
        MtStoreCateSaveOrUpdateVo vo = new MtStoreCateSaveOrUpdateVo();

        Optional.ofNullable(cate).ifPresent(po -> {
            BeanUtil.copyProperties(po, vo);

            //查询特殊资质
            List<MtSecondaryCateSpecialMapEntity> mtSecondaryCateSpecialMapEntities = mtSecondaryCateSpecialMapService.list(Wrappers.<MtSecondaryCateSpecialMapEntity>lambdaQuery()
                    .eq(MtSecondaryCateSpecialMapEntity::getCateId, cateId));
            vo.setSecondaryCateSpecialMap(mtSecondaryCateSpecialMapEntities);

        });

        return ResponseResult.okResult(vo);
    }

    /**
     * @param accountInfo
     * @param vo
     * @return top.lidee.framework.result.ResponseResult
     * @description 根据id修改
     * @author zhangyiheng
     * @date 2024/10/8 14:24
     */
    @Override
    @Transactional
    public ResponseResult update(AccountInfo accountInfo, MtStoreCateSaveOrUpdateVo vo) {
        GlobalCheck.checkAdmin(accountInfo.getManagerId());

        if (savaOrUpdateCateCheck(vo)) return ResponseResult.errorResult(CommonExceptionEnum.RJLMCODEBNWK);

        MtStoreCateEntity cate = CopyBean.copyBean(vo, MtStoreCateEntity.class);

        //删除当前分类下全部特殊资质
        mtSecondaryCateSpecialMapService.remove(Wrappers.<MtSecondaryCateSpecialMapEntity>lambdaQuery()
                .eq(MtSecondaryCateSpecialMapEntity::getCateId, cate.getCategoryId()));

        Optional.ofNullable(vo.getSecondaryCateSpecialMap()).ifPresent(item -> {
            //不等于空保存
            item.forEach(po -> po.setCateId(cate.getCategoryId()));
            mtSecondaryCateSpecialMapService.saveBatch(item);
        });

        this.updateById(cate);

        return ResponseResult.ok();
    }

    /**
     * @param accountInfo
     * @param cateIds
     * @return top.lidee.framework.result.ResponseResult
     * @description 单个或批量删除
     * @author zhangyiheng
     * @date 2024/10/8 14:29
     */
    @Override
    @Transactional
    public ResponseResult delete(AccountInfo accountInfo, Integer[] cateIds) {
        GlobalCheck.checkAdmin(accountInfo.getManagerId());
        List<Integer> ids = Arrays.asList(cateIds);
        //如果是二级分类则删除分类下关联的特殊资质字典数据
        mtSecondaryCateSpecialMapService.remove(Wrappers.<MtSecondaryCateSpecialMapEntity>lambdaQuery()
                .in(MtSecondaryCateSpecialMapEntity::getCateId, ids));

        this.removeByIds(ids);

        return ResponseResult.ok();
    }
}